//bigger opp chart for equipment profil
$(function() {

    (function(Highcharts) {
        var addEvent = Highcharts.addEvent,
                each = Highcharts.each;
        //begrenser drag, slik at den ikke går ut av range
        function filterRange(newY) {
            dragMin = 0,
                    dragMax = 100;
            if (newY < dragMin) {
                newY = dragMin;
            } else if (newY > dragMax) {
                newY = dragMax;
            }
            return newY;
        }
        Highcharts.Chart.prototype.callbacks.push(function(chart) {
            var container = chart.container,
                    dragPoint, dragX, dragY, dragPlotX, dragPlotY;
            chart.redraw();
            addEvent(container, 'mousedown', function(e) {
                var hoverPoint = chart.hoverPoint,
                        options = hoverPoint && hoverPoint.series.options;
                if (options.draggableX) {
                    dragPoint = hoverPoint;

                    dragX = e.pageX;
                    dragPlotX = dragPoint.plotX;
                }

                if (options.draggableY) {
                    dragPoint = hoverPoint;

                    dragY = e.pageY;
                    dragPlotY = dragPoint.plotY + (chart.plotHeight - (dragPoint.yBottom || chart.plotHeight));
                }
            });
            //mousemove event her
            addEvent(container, 'mousemove', function(e) {
                if (dragPoint) {
                    var deltaY = dragY - e.pageY,
                            deltaX = dragX - e.pageX,
                            newPlotX = dragPlotX - deltaX - dragPoint.series.xAxis.minPixelPadding,
                            newPlotY = chart.plotHeight - dragPlotY + deltaY,
                            newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                            newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true),
                            series = dragPoint.series;

                    newY = filterRange(newY);

                    dragPoint.update([newX, newY], false);
                    chart.tooltip.refresh(dragPoint);
                    if (series.stackKey) {
                        chart.redraw();
                    } else {
                        series.redraw();
                    }
                }
            });
            //mouse drop event her
            function drop(e) {
                if (dragPoint) {
                    var deltaX = dragX - e.pageX,
                            deltaY = dragY - e.pageY,
                            newPlotX = dragPlotX - deltaX - dragPoint.series.xAxis.minPixelPadding,
                            newPlotY = chart.plotHeight - dragPlotY + deltaY,
                            series = dragPoint.series,
                            newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                            newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true);

                    newY = filterRange(newY);
                    dragPoint.firePointEvent('drop');
                    dragPoint.update([newX, newY]);

                    dragPoint = dragX = dragY = undefined;
                }
            }
            addEvent(document, 'mouseup', drop);
            addEvent(container, 'mouseleave', drop);
        });

        var colProto = Highcharts.seriesTypes.column.prototype,
                baseDrawTracker = colProto.drawTracker;

        colProto.drawTracker = function() {
            var series = this;
            baseDrawTracker.apply(series);

            each(series.points, function(point) {
                point.tracker.attr(point.shapeArgs.height < 3 ? {
                    'stroke': 'black',
                    'stroke-width': 2,
                    'dashstyle': 'shortdot'
                } : {
                    'stroke-width': 0
                });
            });
        };
    })(Highcharts);
//lager nytt chart objekt (se først highcharts api nøyaktig før du endrer noe her)
    var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'equip_profile',
            animation: false,
            type: 'area'
        },
        xAxis: {
            categories: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '00']
        },
        yAxis: {
            min: 0,
            max: 100,
            title: {
                text: 'in % of total consumption'
            }
        },
        plotOptions: {
            series: {
                cursor: 'ns-resize',
                point: {
                    events: {
                        drop: function() {
                            $('#report_equip').html(
                                    this.category + ' was set to ' + Highcharts.numberFormat(this.y, 0) + ' % of total effect');
                        }
                    }
                }
            },
            column: {
                stacking: 'normal'
            }
        },
        tooltip: {
            yDecimals: 0
        },
        title: {
            text: 'Hourly equipment consumption'
        },
        //data som viser hvilken andel av total effekt brukes  i en gitt timen
        series: [{
                data: [50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50],
                draggableY: true,
                name: 'Hourly consumption %'}]
    });

    //aktiverer reset knappa
    $('#button_reset_equipment').click(function() {
        chart.series[0].setData([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]);
    });


    //aktiverer save as new profile knappa
    $('#button_save_equipment').click(function() {
        var result = chart.series[0].data;
        var s = '';
        for (i = 0; i < result.length; i++) {
            s = s + Highcharts.numberFormat(result[i].y, 0) + ',';
        }
        s = s.substring(0, s.length - 1);
        //objekt som skal sendes til tjener
        var profile = {
            mode: 'profile',
            type: 'equip', //mulige verdier lighting eller equip,depends on profile 
            name: 'name',
            values: s
        };
        //aapner vindu for å legge til navn
        $(function() {
            $("#dialog").dialog({
                modal: true,
                buttons: {
                    close: function() {
                        $(this).dialog("close");
                    },
                    save: function() {
                        //sender ny profil til tjener som håndterer det
                        profile.name = $('#idTxtFldProfileNameBox').val(); //legger til navn
                        $.ajax({
                            type: 'GET',
                            async: false,
                            url: 'index.jsp', //Her skriver URL til servlet som håndterer 
                            data: profile, //det som vi sender
                            dataType: 'html', //det som vi får tilbake (kind of data we will get)
                            success: function(data, textStatus) { //haandterer svar 
                                $('#dialog').html("Profile saved successfully");
                                chart.series[0].setData([50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50]);
                            },
                            error: function(data, textstatus) {
                                $('#dialog').html('ooops, something goes wrong');
                            }
                        });
                        $('#dialog').dialog('option', 'buttons', [
                            {
                                text: "close",
                                click: function() {
                                    $(this).dialog("close");
                                }
                            }
                        ]);
                    }
                }
            });
            var nameBoxForm = '<input type="text" id="idTxtFldProfileNameBox" maxlength="64"/>';
            $('#dialog').html(nameBoxForm);
        });
    });
    $.getJSON("AjaxHandler", "mode=getpatternnames&type=equip", function(data) {
        var option = "<option class=\"item_element\">current</option>";
        $.each(data, function(i, item) {
            option += "<option class=\"item_element\">" + item + "</option>";
        });
        $("#idSlctlstEquipPrfl").html(option);
    });

    var currentData;
    var currentValues;
    $("#idSlctlstEquipPrfl").focus(function() {
        if ($("#idSlctlstEquipPrfl option:selected").text() === "current") {
            currentData = chart.series[0].data;
            currentValues = '';
            for (i = 0; i < currentData.length; i++) {
                currentValues = currentValues + Highcharts.numberFormat(currentData[i].y, 0) + ',';
            }
            currentValues = currentValues.substring(0, currentValues.length - 1);
        }
    });
    $("#idSlctlstEquipPrfl").change(function() {
        $("#idSlctlstEquipPrfl option:selected").each(function() {
            var name = $(this).text();
            if (name === "current") {
                chart.series[0].setData("[" + currentValues + "]");
            }
            else {
                $.getJSON("AjaxHandler", "mode=getusageprofile&name=" + name + "&type=equip", function(data) {
                    chart.series[0].setData(data.data);
                });
            }
        });
    });

    $("#button_back_equipment").click(function() {
        window.location.replace("index.jsp?do=create");
    });
});